<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/24 0024
 * Time: 16:33
 */

namespace app\controllers;

use app\models\User;
use yii;
use yii\web\Controller;
use yii\web\Response;

class BaseController extends Controller
{
    public $enableCsrfValidation = false;
    public $user_id = 0;
    public $params;
    public $data = array(
        'status' 	=> 1,
        'error' 	=> array('errorno' => 0, 'errormsg' => 'success'),
        'data'		=> array()
    );
    /**
     *  返回成功json数据
     * @param array $data
     * @param integer $stauts
     * @return array
     */
    public  function response($data = null, $stauts = 1)
    {
        if($data!=null) $this->data[ 'data' ] = $data;
        echo json_encode($this->data);
        exit;
    }

    /**
     * 返回错误信息
     * @param string $no 状态码
     * @param string $msg 错误信息
     * @return array
     */
    protected function error($no='00001',$msg='一般错误')
    {
        $this->data['status'] = 0;
        $this->data[ 'error' ] = array( 'errorno' => $no, 'errormsg' => $msg, );
        return $this->response(null, 0);
    }

    public function beforeAction($action)
    {
        $this->validate();
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    public function  validate(){
        if($this->module->requestedRoute == "index/index" || $this->module->requestedRoute == "order/notify"){
            return true;
        }
        $this->params = array_merge(Yii::$app->request->get(), Yii::$app->request->post());
        if(!(isset($this->params['flagsign']) && $this->params['flagsign']==1)){
            $this->_checkVerify();
        }

        $islogin=$this->checkLogin();
        if(!$islogin &&  $this->user_id==0)
        {
            $this->data[ 'status' ] = 0;
            $this->data[ 'error' ] = array( 'errorno' => "401", 'errormsg' => '请登陆' );
            $this->data['data'] = new \stdClass();
            echo json_encode($this->data);exit();
        }
        return true;
    }

    public function _checkVerify(){

        $post = array_merge(Yii::$app->request->get(), Yii::$app->request->post());

        if(!isset($post['appid']) || !isset($post['nonce']) || !isset($post['timestamp']) || !isset($post['timediff'])){
            $this->error('999996', '缺少验签参数');
        }

        $sort_post=$post;
        if(isset($sort_post['signature']))
            unset($sort_post['signature']);
        ksort($sort_post,2);

        $final_post = "";
        foreach($sort_post as $k=>$v){
            $final_post .= urlencode($v);
        }

        $appKey = Yii::$app->params['appversioninfo'][$post['appid']];
        $signature=sha1($final_post.$appKey);
        //判断非空
        if (empty($post)){
            $this->error('999999', '没有传入数据');
        }

        //判断时间戳(误差)
        if((abs($post['timestamp']+$post['timediff']-time()) > 60*10)){
            $this->error('999998', '超时请求');
        }

        //验证签名
        if ($signature!=$post['signature']) {
            $this->error('999997', '签名错误');
        }
    }

    public function checkLogin()
    {
        if(\Yii::$app->user->isGuest){
            if(!isset($_REQUEST['access_token']) ||  !$user = User::findIdentityByAccessToken($_REQUEST['access_token'])){
                $controllerID = Yii::$app->controller->id;
                $actionID = Yii::$app->controller->action->id;
                $nologin=Yii::$app->params['nologin'];
                if(isset($nologin[$controllerID]) && in_array($actionID,$nologin[$controllerID]))
                    return true;
                else
                    return false;
            }else{
                $this->user_id= $user['user_id'];
                return true;
            }
        }else{
            $this->user_id= \Yii::$app->user->getId();
            return true;
        }
    }

    public function getQueryparams($name,$defaultValue,$data_type='')
    {
        $returnvalue=isset($this->params[$name]) ? $this->params[$name] : $defaultValue;
        if(isset($this->params[$name])&&$data_type!='')
        {
            switch ($data_type)
            {
                case 'int':
                    //echo $this->params[$name];die;
                    //var_dump(filter_var($this->params[$name],FILTER_VALIDATE_INT));die;
                    if(filter_var($this->params[$name],FILTER_VALIDATE_INT)||filter_var($this->params[$name],FILTER_VALIDATE_INT)===0)
                    {
                        $returnvalue=(int)$this->params[$name];
                    }
                    else
                    {
                        $returnvalue=$defaultValue;
                    }
                    break;
                case 'float':
                    if(filter_var($this->params[$name],FILTER_VALIDATE_FLOAT)||filter_var($this->params[$name],FILTER_VALIDATE_FLOAT)===0.0)
                    {
                        $returnvalue=(float)$this->params[$name];
                    }
                    else
                    {
                        $returnvalue=$defaultValue;
                    }
                    //$returnvalue= filter_var($this->params[$name],FILTER_VALIDATE_FLOAT)?(float)$this->params[$name]:$defaultValue;
                    break;
                default:
                    $returnvalue= is_string($this->params[$name])?$this->params[$name]:$defaultValue;
                    break;
            }
        }

        return $returnvalue;
    }
}
